<?php

require('simplehtmldom/simple_html_dom.php');
require('get_redirect_url.php');

/**
 * follows pseudocode to implement a basic skeleton for the app
 */

$entryNodes = array();

class Page {
	var $pageDom;
	var $url;
	var $title;
	
	function fetch() {
		$this->pageDom = file_get_html($this->url);
	}
	
	function buildHref($url) {
		$url = str_replace(	array('?', ' '), 
							array('' , '%20'),
							$url);
		if($url[strlen($url) -1] == '?')
			$url = substr($url,0,strlen($url)-1);
		if($url[0] == '/')
			return substr($this->url, 0, stripos($this->url, '/', 7)) . $url;
		else if($url[0] == 'h')
			return $url;
		else return substr($this->url, 0, strripos($this->url,'/') +1) . $url;
	}
}

class categoryPage extends Page {
	var $subcategories = array();
	var $hasSubs;
	
	function __construct($urlArg, $titleArg = '', $hasSubcategoriesArg = true) {
		echo "Building new category Page @ url {$urlArg}\n";
		$this->url = $urlArg;
		$this->hasSubs = $hasSubcategoriesArg;
		if($hasSubcategoriesArg)
			$this->fetch();
		$this->title = $titleArg; 
	}
	
	function __destruct() {
		unset($this->subcategories);
		if(isset($this->pageDom))
			unset($this->pageDom);
	}
	
	function getSubcategories() {
		return $this->subcategories;
	}
	
	function getEntryPage() {
		if($this->isEntry())
			return new entryPage($this->url, $this->title); 
	}
	
	function isEntry() {
		return !$this->hasSubs;
	}
	
	function hasSubcategories() {
		if(count($this->pageDom->find('ul.category-letter li a')) == 0)
			return true;
		else return false;
	}
	
	function fetchCategories() {
		if($this->hasSubcategories()) {
			$subcategoryNodes = $this->pageDom->find('div.category-box h3 a');
			foreach($subcategoryNodes as $subcategoryNodesId=>$subcategoryNodesVal) {
				$subcategoryNodes[$subcategoryNodesId] = array(	'title' => $subcategoryNodesVal->title,
																'href'	=> $subcategoryNodesVal->href);
			}
			unset($this->pageDom);
			foreach( $subcategoryNodes as $subcategoryNode) {
				$subCategoryEntry = new categoryPage($this->buildHref($subcategoryNode['href']), 	( $this->title ? $this->title . ' > ' : '' ) . 
																									$subcategoryNode['title']);
				$subCategoryEntry->fetchCategories();
				foreach($subCategoryEntry->getSubcategories() as $subcategory) {
					$this->subcategories[] = $subcategory;
				}
				unset($subCategoryEntry);
			}
		} else {
			$subcategoryNodes = $this->pageDom->find('ul.category-letter li a');
			foreach($subcategoryNodes as $subcategoryNodesId=>$subcategoryNodesVal) {
				$subcategoryNodes[$subcategoryNodesId] = array(	'title' => $subcategoryNodesVal->title,
																'href'	=> $subcategoryNodesVal->href);
			}
			unset($this->pageDom);
			foreach( $subcategoryNodes as $subcategoryNode) {
				$this->subcategories[] = new categoryPage( $this->buildHref($subcategoryNode['href']), 	( $this->title ? $this->title . ' > ' : '' ) . 
																										$subcategoryNode['title'], false); 
			}
		}
	}
}

class entryPage extends Page {
	var $entries = array();
	var $pageNum = 0;
	
	function __construct($urlArg, $titleArg = '') {
		echo "Building new entry Page @ url {$urlArg}\n";
		$this->url = $urlArg;
		$this->title = $titleArg; 
	}
	
	function fetchEntries() {
		$this->fetch();
		$entryNodes = $this->pageDom->find('div.listing-client-line-pg');
		foreach($entryNodes as $entryNode) {
			$this->entries[] = array(	'Name'		=> trim($entryNode->find('div.client-identifying-pg h3',0)->plaintext),
										'Address'	=> $entryNode->find('address p span.locality',0)->plaintext,
										'City'		=> $entryNode->find('address p.street-address',0)->plaintext,
										'CAP'		=> $entryNode->find('address p span.postal-code',0)->plaintext,
										'Region'	=> substr($entryNode->find('address p span.region',0)->plaintext, 1, 2),
										'WebSite'	=> $entryNode->find('div.link_prodotti a.lnkwww',0)->href );
		}
	}
	
	function getEntries() {
		return $this->entries;
	}
	
	function isLast() {
		return(count($this->pageDom->find('a[title=successiva]')) == 0);
	}
	
	function getPage() {
		return $this->pageNum;
	}
	
	function next() {
		if($this->isLast()) {
			unset($this->pageDom);
			return false;	
		} else {
			$this->pageNum++;
			$this->entries = array();
			$this->url = $this->buildHref($this->pageDom->find('a[title=successiva]',0)->href);
			return true;
		}
	}
}

class cvsWriter {
	var $fileHandle;
	var $fileBuffer = '';
	var $columns;
	
	function __construct($filename) {
		$this->fileHandle = fopen($filename,'w');
	}
	
	function setColumns($columnArray) {
		
	}
	
	function writeLine($entryArray) {
		$currLine = array();
		foreach($columns as $column) {
			$currLine[] = isset($entryArray[$column]) 	?	$entryArray[$column] : '';
		}
		$this->fileBuffer .= implode(',',$currLine) . "\n";
	}
	
	function flush() {
		fwrite($this->fileHandle, $this->fileBuffer);
	}
}

$cvsFile = new cvsWriter('output.cvs');
$cvsFile->setColumns(array('Col1', 'Col2', 'Col3'));

//$mainCategoryPage = new categoryPage('http://www.paginegialle.it/cat/pagine_gialle_naviga.html');
$mainCategoryPage = new categoryPage('http://www.paginegialle.it/cat/informatica_consulenza_e_servizi.html');
//$mainCategoryPage = new categoryPage('http://www.paginegialle.it/cat/informatica_e_telecomunicazioni.html');

$mainCategoryPage->fetchCategories();

foreach($mainCategoryPage->getSubcategories() as $subcategory) {
	$entryPage = $subcategory->getEntrypage();
	echo "::Fetching {$subcategory->title} \n";
	do {
		$entryPage->fetchEntries();
		echo "::::page" . $entryPage->getPage() .", fetched " . count($entryPage->getEntries()) . "\n";
		foreach($entryPage->getEntries() as $entry) {
			print_r($entry);
			//$cvsFile->writeLine($entry);
		}
	} while($entryPage->next());
}

$cvsFile->flush();

?>